import axios from 'axios'
import { Loading, Message } from 'element-ui'
import router from '../router';

let loadingInstance;
function startLoading() {
  loadingInstance = Loading.service({
    lock: true,
    text: '拼命加载中...',
    background: 'rgba(0, 0, 0, .7)'
  })
}

function endLoading() {
  loadingInstance.close()
}

// 请求拦截 设置统一header
axios.interceptors.request.use(config => {
  startLoading()

  // 验证token
  if (localStorage.eleToken) {
    config.headers.Authorization = localStorage.eleToken
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截  401 token过期处理
axios.interceptors.response.use(response => {
  endLoading()
  return response
}, error => {
  endLoading()
  Message.error(error.response.data)

  const { status } = error.response
  if (status === 401) {
    Message.error('token值无效，请重新登录')
    // 清空token
    localStorage.removeItem('eleToken')

    // 跳转到login
    router.push('login')
  }

  return Promise.reject(error)
})


export default axios